#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/4/10 16:40
# @Author  : harry
import threading

import requests
from rest_framework import serializers
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated

from dvadmin.utils.json_response import DetailResponse, ErrorResponse
from dvadmin.utils.serializers import CustomModelSerializer
from dvadmin.utils.viewset import CustomModelViewSet
from dvadmin_wechat.filters import FanTagsFilterSet
from dvadmin_wechat.models import FanTags, OfficialAccountManagement, FanManagement
from dvadmin_wechat.tools import sync_tags


def get_access_token(data):
    res = requests.get(
        url='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={}&secret={}'.format(
            data.appid, data.app_secret))
    if "access_token" in res.text:
        return res.json().get('access_token')

    else:
        return False


class FanTagsCreateSerializer(CustomModelSerializer):
    sum_num = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = FanTags
        fields = "__all__"
        read_only_fields = ["id"]

    def get_sum_num(self, obj):
        return FanManagement.objects.filter(fan_tags=obj).count()

    def validate(self, attrs):
        request = self.context.get("request")
        official_account_management_id = request.data.get("official_account_management_id")
        name = request.data.get("name")
        tagsid = request.data.get("tagsid")
        if not official_account_management_id:
            raise serializers.ValidationError('公众号id必传')
        if not name:
            raise serializers.ValidationError("标签名必传")
        o_a_m = OfficialAccountManagement.objects.filter(id=official_account_management_id).first()
        if not o_a_m:
            raise serializers.ValidationError("请输入正确的公众号")
        access_token = get_access_token(o_a_m)
        if access_token:
            data = {
                'tag': {'name': name}
            }
            res = requests.post(
                url='https://api.weixin.qq.com/cgi-bin/tags/create?access_token={}'.format(access_token),
                json=data)
            if "errcode" not in res.text:
                attrs['tagsid'] = res.json().get("tag").get("id")
                attrs['name'] = name
                attrs['official_account_management_id'] = official_account_management_id
            else:
                raise serializers.ValidationError("请输入正确的信息")
        else:
            raise serializers.ValidationError("请输入正确的信息")
        return attrs


class FanTagsViewSet(CustomModelViewSet):
    """
    菜单管理接口
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    queryset = FanTags.objects.filter(official_account_management__status=1).exclude(tagsid=2)
    serializer_class = FanTagsCreateSerializer
    create_serializer_class = FanTagsCreateSerializer
    update_serializer_class = FanTagsCreateSerializer
    search_fields = ['name', "official_account_management__name"]
    # filter_fields = ['name', 'official_account_management_id', 'tagsid']
    filter_class = FanTagsFilterSet

    @action(methods=["GET"], detail=False, permission_classes=[IsAuthenticated])
    def sync(self, request):
        """同步标签信息"""
        for th in threading.enumerate():
            if th.name == "sync_tags_111":
                return ErrorResponse(msg="上一次同步标签还未完成,请稍后再试")
        official_account_management_id = self.request.query_params.get("official_account_management_id")
        t = threading.Thread(name='sync_tags_111', target=sync_tags,
                             kwargs={'official_account_management': official_account_management_id})
        t.daemon = True
        t.start()
        return DetailResponse(data=None, msg="同步成功")

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        # print(instance.id, instance.name)
        access_token = get_access_token(instance.official_account_management)
        data = {
            "tag": {'id': instance.tagsid}
        }
        res = requests.post(url=' https://api.weixin.qq.com/cgi-bin/tags/delete?access_token={}'.format(access_token),
                            json=data)
        if "ok" in res.json().get("errmsg"):
            instance.delete()
        else:
            return DetailResponse(data=[], msg=res.json().get("errmsg"))
        return DetailResponse(data=[], msg="删除成功")
